package pers.liu.yibandemo.service;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.liu.yibandemo.entity.Parent;
import pers.liu.yibandemo.mapper.ParentMapper;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import java.util.List;

@Service
public class ParentService extends ServiceImpl<ParentMapper, Parent> {

    @Autowired
    private ParentMapper parentMapper;

    // 添加家长用户
    public void addParent(Parent parent) {
        System.out.println(parent);
        if(parent.getParentChildId()!=null && !parent.getParentChildId().isEmpty()){
            parent.setParentState(true);
        }
        parentMapper.insert(parent);
    }

    // 根据家长用户ID查询家长信息
    public Parent getParentById(Long parentId) {
        return parentMapper.selectById(parentId);
    }

    // 查询所有家长用户
    public List<Parent> getAllParents() {
        return parentMapper.selectList(null);
    }
    public IPage<Parent> getParentsByPage(int pageNum, int pageSize){
        Page<Parent> page = new Page<>(pageNum, pageSize);
        Page<Parent> result = parentMapper.selectPage(page, null);
        return result;
    }
    // 更新家长用户信息
    public void updateParent(Parent parent) {
        if(parent.getParentChildId()!=null && !parent.getParentChildId().isEmpty()){
            parent.setParentState(true);
        }else
            parent.setParentState(false);
        parentMapper.updateById(parent);
    }

    // 删除家长用户
    public void deleteParent(Long parentId) {
        parentMapper.deleteById(parentId);
    }

    // 获取所有家长用户的ID并封装成JSON格式的字符串
    public String getAllParentIdsAsJson() {
        List<Parent> allParents = parentMapper.selectList(null);

        JSONArray array = new JSONArray();
        for (Parent parent : allParents) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("userid",parent.getYbUserId());
            jsonObject.set("username",parent.getYbUserName());
            array.add(jsonObject);
        }

        JSONObject result = new JSONObject();
        result.set("users", array);

        return JSONUtil.toJsonStr(result);
    }
}
